#!/bin/bash

# 初始化环境变量
app_service="${app_service}"
app_service_port="${app_service_port:-3000}"
app_service_dist_zip="${app_service_dist_zip:-/tmp/dist.zip}"
app_service_dist_url="${app_service_dist_url}"
app_service_container_name="${app_service_container_name}"
app_service_network="${app_service_network}"
app_service_docker_max_memory="${app_service_docker_max_memory:-1280M}"

service_image=server.laoshuzi.top:15092/env-run/node-24-alpine:1.0.0
dist_path=~/web/${app_service}/dist


check_container() {
  if docker ps --format '{{.Names}}' | grep -q "^${app_service_container_name}$"; then
    echo "容器存在!"
    return 0
  else
    echo "容器不存在!"
    return 1
  fi
}

run_service() {
  echo "创建网络"
  echo "docker network create --attachable --driver bridge ${app_service_network}"
  docker network create --attachable --driver bridge ${app_service_network} || true

  echo "清理旧容器"
  echo "docker rm -f ${app_service_container_name}"
  docker rm -f ${app_service_container_name} || true

  echo "创建配置目录"
  echo "mkdir -p ${dist_path}"
  mkdir -p ${dist_path}

  echo "下载解压资源文件"
  echo "wget -O ${app_service_dist_zip} ${app_service_dist_url}"
  wget -O ${app_service_dist_zip} ${app_service_dist_url}
  echo "rm -rf ${dist_path}/*"
  rm -rf ${dist_path}/*
  echo "unzip ${app_service_dist_zip} -d ${dist_path}"
  unzip ${app_service_dist_zip} -d ${dist_path}

  echo "启动容器"
  echo "docker run --name ${app_service_container_name} \
            --restart=always \
            --network ${app_service_network} \
            -v ${dist_path}:/app \
            -p ${app_service_port}:3000 \
            -m ${app_service_docker_max_memory} \
            -d ${service_image}"
  docker run --name ${app_service_container_name} \
    --network ${app_service_network} \
    -v ${dist_path}:/app \
    -p ${app_service_port}:3000 \
    -m ${app_service_docker_max_memory} \
    -d ${service_image}
}

reload_service() {
  echo "下载解压资源文件"
  echo "wget -O ${app_service_dist_zip} ${app_service_dist_url}"
  wget -O ${app_service_dist_zip} ${app_service_dist_url}
  echo "rm -rf ${dist_path}/*"
  rm -rf ${dist_path}/*
  echo "unzip ${app_service_dist_zip} -d ${dist_path}"
  unzip ${app_service_dist_zip} -d ${dist_path}

  echo "重启容器"
  echo "docker restart ${app_service_container_name}"
  docker restart ${app_service_container_name}
}


clean_service() {
  echo "清除容器"
  echo "docker stop ${app_service_container_name}"
  docker stop ${app_service_container_name}

  echo "清除镜像"
  echo "docker rm ${app_service_container_name}"
  docker rm ${app_service_container_name}
}

# 主逻辑
case $1 in
  check)
    check_container
    ;;
  run)
    if check_container; then
      reload_service
    else
      run_service
    fi
    ;;
  clean)
    clean_service
    ;;
  *)
    echo "Usage: $0 {check|run|clean}"
    exit 1
    ;;
esac